<template>
  <el-container class="water-monitor-layout" fullscreen>
    <!-- 左侧区域-水表树形结构 -->
    <el-aside width="280px" class="aside-panel">
      <div class="aside-header">
        <el-icon class="header-icon"><LocationFilled /></el-icon>
        <span class="header-title">24小时流量</span>
      </div>
      <!-- 区域-水表树形组件 -->
      <el-tree
          ref="areaMeterTree"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="true"
          :filter-node-method="filterTreeNode"
          @node-click="handleNodeSelect"
          class="tree-container"
          v-loading="treeLoading"
          loading-text="加载区域与水表数据中..."
      >
        <!-- 自定义节点图标（区分区域/水表） -->
        <template #default="{ node }">
          <div class="node-content">
            <!-- 区域节点图标 -->
            <el-icon v-if="node.type === 'area'" class="node-icon area-icon">
              <OfficeBuilding />
            </el-icon>
            <!-- 水表节点图标 -->
            <el-icon v-else-if="node.type === 'meter'" class="node-icon meter-icon">
              <WaterFilled />
            </el-icon>
            <span class="node-label">{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
    </el-aside>

    <!-- 右侧主内容区（时间筛选 + 图表/表格） -->
    <el-main class="main-content">
      <!-- 时间筛选栏 -->
      <div class="time-filter-bar">
        <!-- 起止时间选择器 -->
        <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
            class="date-picker"
            :picker-options="datePickerOptions"
        />
        <!-- 快捷时间按钮组 -->
        <el-button-group class="quick-time-group">
          <el-button size="small" type="primary" @click="setQuickTime('today')">当日</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('yesterday')">昨天</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('week')">本周</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('month')">当月</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('lastMonth')">上月</el-button>
        </el-button-group>

        <!-- 新增：导出图表按钮 -->
        <el-button
            size="small"
            type="primary"
            icon="Download"
            @click="handleExportChart"
        >
          导出图表
        </el-button>
      </div>

      <!-- 数据展示方式切换标签 -->
      <el-tabs v-model="activeTab" class="data-tabs" style="margin-bottom: 16px;">
        <el-tab-pane label="折线图" name="chart"></el-tab-pane>
        <el-tab-pane label="表格" name="table"></el-tab-pane>
      </el-tabs>

      <!-- 数据展示区域 -->
      <div class="data-container">
        <!-- ECharts流量图表 -->
        <div class="chart-container" v-if="activeTab === 'chart'">
          <ECharts
              ref="flowChart"
              :option="chartOption"
              class="chart"
              v-loading="chartLoading"
              loading-text="加载小时流量数据中..."
          />
          <!-- 无数据提示 -->
          <div class="empty-tip" v-if="!chartLoading && isChartEmpty">
            <el-icon class="empty-icon"><InfoFilled /></el-icon>
            <p class="empty-text">请选择水表并设置时间范围查询小时数据</p>
          </div>
        </div>

        <!-- 表格展示 -->
        <div class="table-container" v-if="activeTab === 'table'">
          <el-table
              :data="tableData"
              border
              v-loading="tableLoading"
              loading-text="加载小时数据中..."
              style="width: 100%;"
          >
            <el-table-column
                prop="valueTime"
            label="小时时间"
            width="200"
            align="center"
            >
            <template #default="scope">
              {{ formatDateTime(scope.row.valueTime) }}
            </template>
            </el-table-column>
            <el-table-column
                prop="value"
            label="小时水量(吨)"
            align="center"
            />
          </el-table>
          <!-- 表格无数据提示 -->
          <div class="empty-tip" v-if="!tableLoading && tableData.length === 0">
            <el-icon class="empty-icon"><InfoFilled /></el-icon>
            <p class="empty-text">当前时间范围内无小时数据</p>
          </div>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElButtonGroup, ElButton, ElDatePicker, ElTree, ElIcon, ElTabs, ElTabPane, ElTable, ElTableColumn } from 'element-plus'
// 引入图标
import { Download,LocationFilled, OfficeBuilding, InfoFilled } from '@element-plus/icons-vue'
// 引入ECharts组件
import ECharts from '@/components/ECharts/index.vue'
// 引入API方法
import { listArea } from '@/api/water/area'
import { listElement } from '@/api/water/element'
import { listHourdata } from '@/api/water/hourdata'  // 小时数据API
// 时间处理工具
import dayjs from 'dayjs'

const flowChart = ref(null);

// ======================== 响应式数据 ========================
// 分页相关配置
const currentPage = ref(1)
const pageSize = ref(50)
const totalData = ref([])  // 存储小时数据集合（字段为value和valueTime）

// 树形结构数据
const treeData = ref([])
const treeProps = ref({
  children: 'children',
  label: 'label'
})
const selectedNode = ref(null)
const dateRange = ref([])
// 加载状态
const treeLoading = ref(false)
const chartLoading = ref(false)
const tableLoading = ref(false)

// 标签页切换
const activeTab = ref('chart')

// 表格数据（绑定后端返回的value和valueTime字段）
const tableData = ref([])

// 日期选择器配置
const datePickerOptions = ref({
  timePickerOptions: {
    start: '00:00',
    end: '23:59',
    step: '00:01'
  }
})

// 图表配置（适配后端字段）
const chartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    formatter: '{b}<br/>小时水量: {c} 吨'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],  // 存储valueTime
    axisLabel: {
      formatter: (val) => dayjs(val).format('MM-DD HH时'),
      interval: 0,
      show: true,
      rotate: 45,
    }
  },
  yAxis: {
    type: 'value',
    name: '小时水量 (吨)',
    min: 0,
    splitLine: { show: true, lineStyle: { type: 'dashed' } }
  },
  series: [{
    name: '小时流量',
    type: 'line',
    data: [],  // 存储value
    smooth: true,
    itemStyle: { color: '#409EFF' },
    lineStyle: { width: 2 }
  }]
})

// 图表无数据标识
const isChartEmpty = computed(() => {
  return chartOption.value.series[0].data.length === 0
})

// ======================== 页面初始化 ========================
onMounted(() => {
  initAreaMeterTree()
  setQuickTime('today')
})

// ======================== 树形结构逻辑 ========================
/**
 * 初始化区域-水表树形数据
 */
const initAreaMeterTree = async () => {
  treeLoading.value = true
  try {
    // 获取所有区域
    const areaRes = await listArea({ pageNum: 1, pageSize: 1000 });
    if (areaRes.code !== 200) throw new Error('获取区域数据失败')
    // 获取所有水表
    const meterRes = await listElement({ pageNum: 1, pageSize: 1000 })
    if (meterRes.code !== 200) throw new Error('获取水表数据失败')

    // 构建区域树形
    const areaTree = buildAreaTree(areaRes.rows)
    // 分配水表到区域
    const finalTree = assignMetersToArea(areaTree, meterRes.rows)

    treeData.value = finalTree
  } catch (err) {
    ElMessage.error(err.message || '初始化数据失败')
    console.error('树形数据初始化错误：', err)
  } finally {
    treeLoading.value = false
  }
}

/**
 * 构建区域树形结构
 */
const buildAreaTree = (areas) => {
  const areaMap = new Map()
  const rootAreas = []

  areas.forEach(area => {
    areaMap.set(area.id, {
      ...area,
      type: 'area',
      label: area.areaName,
      children: []
    })
  })

  areaMap.forEach(area => {
    const parentId = area.parentAreaId
    if (!parentId || parentId === 0 || !areaMap.has(parentId)) {
      rootAreas.push(area)
    } else {
      const parentArea = areaMap.get(parentId)
      parentArea.children.push(area)
    }
  })

  return rootAreas
}

/**
 * 分配水表到对应区域
 */
const assignMetersToArea = (areaTree, meters) => {
  const [meterWithArea, meterWithoutArea] = meters.reduce((acc, meter) => {
    const hasFirstArea = !['', null, undefined].includes(meter.firstAreaId)
    const hasNegativeArea = !['', null, undefined].includes(meter.negativeAreaId)

    if (hasFirstArea || hasNegativeArea) {
      acc[0].push(meter)
    } else {
      acc[1].push(meter)
    }
    return acc
  }, [[], []])

  const traverse = (nodes) => {
    nodes.forEach(node => {
      if (node.type === 'area') {
        const matchedMeters = meterWithArea.filter(meter => {
          return meter.firstAreaId === node.id || meter.negativeAreaId === node.id
        }).map(meter => {
          const isNegativeMeter = meter.negativeAreaId === node.id;
          return {
            ...meter,
            type: 'meter',
            label: isNegativeMeter ? `${meter.elemName}-反向表` : meter.elemName,
            children: null
          };
        })

        node.children = [...node.children, ...matchedMeters]

        if (node.children && node.children.length > 0) {
          traverse(node.children)
        }
      }
    })
  }

  traverse(areaTree)

  if (meterWithoutArea.length > 0) {
    const otherArea = {
      id: 'other_area_placeholder',
      type: 'area',
      label: '其他（无区域的水表）',
      children: meterWithoutArea.map(meter => ({
        ...meter,
        type: 'meter',
        label: meter.elemName,
        children: null
      }))
    }
    areaTree.push(otherArea)
  }

  return areaTree
}

/**
 * 树形节点选择事件
 */
const handleNodeSelect = (node) => {
  if (node.type === 'meter') {
    selectedNode.value = node
    fetchHourFlowData()
  }
}

// ======================== 时间筛选逻辑 ========================
/**
 * 设置快捷时间范围
 */
const setQuickTime = (type) => {
  let endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let startTime = ''

  switch (type) {
    case 'today':
      startTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
      endTime = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
      break
    case 'yesterday':
      startTime = dayjs().subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
      endTime = dayjs().subtract(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss')
      break
    case 'week':
      startTime = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
      endTime = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
      break
    case 'month':
      startTime = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
      endTime = dayjs().endOf('month').format('YYYY-MM-DD HH:mm:ss')
      break
    case 'lastMonth':
      startTime = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss')
      endTime = dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD HH:mm:ss')
      break
  }

  dateRange.value = [startTime, endTime]
  if (selectedNode.value) fetchHourFlowData()
}

/**
 * 手动选择时间范围触发
 */
const handleDateChange = () => {
  if (selectedNode.value) fetchHourFlowData()
}

// ======================== 小时数据查询逻辑（核心适配） ========================
/**
 * 查询水表小时流量数据（适配后端value和valueTime字段）
 */
const fetchHourFlowData = async () => {
  if (!selectedNode.value || !dateRange.value[0] || !dateRange.value[1]) {
    ElMessage.warning('请先选择水表并设置时间范围')
    return
  }

  chartLoading.value = true
  tableLoading.value = true
  currentPage.value = 1
  totalData.value = []
  const pageSizeVal = pageSize.value
  let hasMoreData = true

  try {
    while (hasMoreData) {
      const params = {
        meterId: selectedNode.value.id,  // 水表ID
        startTime: dateRange.value[0],   // 开始时间
        endTime: dateRange.value[1],     // 结束时间
        pageNum: currentPage.value,      // 分页参数
        pageSize: pageSizeVal
      }

      // 调用小时数据API
      const res = await listHourdata(params)
      if (res.code !== 200 || !Array.isArray(res.rows)) {
        throw new Error(`第${currentPage.value}页小时数据请求失败，请重试`)
      }

      const currentPageData = res.rows
      totalData.value.push(...currentPageData)

      hasMoreData = currentPageData.length === pageSizeVal
      currentPage.value++
    }

    // 按时间排序（使用后端返回的valueTime字段）
    const sortedData = totalData.value.sort((a, b) => {
      return new Date(a.valueTime) - new Date(b.valueTime)
    })

    // 更新图表数据（映射valueTime和value字段）
    chartOption.value.xAxis.data = sortedData.map(item => item.valueTime)
    chartOption.value.series[0].data = sortedData.map(item => item.value)

    // 更新表格数据
    tableData.value = sortedData

    if (sortedData.length === 0) {
      ElMessage.info('当前时间范围内无小时流量数据')
    }

  } catch (err) {
    ElMessage.error(err.message || '小时流量数据查询失败')
    console.error('分页请求小时数据错误：', err)

  } finally {
    chartLoading.value = false
    tableLoading.value = false
  }
}

/**
 * 格式化日期时间显示（使用valueTime字段）
 */
const formatDateTime = (dateTime) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// ======================== 树形过滤 ========================
const filterTreeNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}
// 父组件 handleExportChart 中修改：
const handleExportChart = async () => {
  // 1. 空值校验（保持不变）
  if (!selectedNode.value) { ElMessage.warning('请先选择水表'); return; }
  if (!dateRange.value[0] || !dateRange.value[1]) { ElMessage.warning('请设置时间范围'); return; }

  // 2. 修正：通过 ref 变量获取子组件实例（关键！）
  const chartComponent = flowChart.value; // 替换原来的 $refs.flowChart
  if (!chartComponent) {
    ElMessage.error('图表组件未加载，请稍后重试');
    return;
  }

  // 3. 新增：通过子组件方法获取 myChart（后续步骤会在子组件添加此方法）
  const echartsInstance = chartComponent.getEchartsInstance();
  if (!echartsInstance) {
    ElMessage.error('ECharts实例未初始化，请稍后重试');
    return;
  }

  // 后续代码（修改标题、生成图片等）保持不变，但将所有 "chartComponent.myChart" 改为 "echartsInstance"
  try {
    const originalTitle = chartOption.value.title || null;
    const meterName = selectedNode.value.label;
    const timeRangeText = `${dayjs(dateRange.value[0]).format('YYYY-MM-DD HH:mm')} 至 ${dayjs(dateRange.value[1]).format('YYYY-MM-DD HH:mm')}`;

    chartOption.value.title = {
      text: `水表：${meterName} | 时间范围：${timeRangeText}`,
      left: 'center',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    };

    // 调用子组件的 setOption 方法更新图表（保持不变）
    chartComponent.setOption(chartOption.value);

    // 延迟导出（确保标题渲染）
    setTimeout(() => {
      // 4. 修正：用获取到的 echartsInstance 生成图片
      const imgBase64 = echartsInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#ffffff'
      });

      // 下载逻辑（保持不变）
      const link = document.createElement('a');
      link.href = imgBase64;
      const fileName = `${meterName}_${dayjs(dateRange.value[0]).format('YYYYMMDDHHmm')}_${dayjs(dateRange.value[1]).format('YYYYMMDDHHmm')}.png`;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 恢复原始标题（保持不变）
      chartOption.value.title = originalTitle;
      chartComponent.setOption(chartOption.value);

      ElMessage.success('图表导出成功');
    }, 100);

  } catch (error) {
    ElMessage.error(`导出失败：${error.message}`);
    console.error('图表导出错误：', error);
  }
};

</script>

<style scoped>
/* 样式保持不变 */
.water-monitor-layout {
  display: flex;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.aside-panel {
  height: 100%;
  background-color: #f8f9fa;
  border-right: 1px solid #e9ecef;
}

.aside-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}

.header-icon {
  color: #409eff;
  font-size: 18px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.tree-container {
  height: calc(100% - 84px);
  overflow-y: auto;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-icon {
  font-size: 14px;
}

.area-icon {
  color: #409eff;
}

.meter-icon {
  color: #67c23a;
}

.main-content {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.time-filter-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.date-picker {
  width: 480px;
}

.quick-time-group {
  display: flex;
  gap: 8px;
}

.data-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chart-container {
  position: relative;
  height: 100%;
  width: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}

.table-container {
  position: relative;
  height: 100%;
  width: 100%;
  overflow: auto;
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 8px;
}
</style>
